<template>
  <div class="target-management-container">
    <!-- 头部操作区域 -->
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd" class="add-target-btn">
        <el-icon><Plus /></el-icon>
        新增目标
      </el-button>

      <el-button type="info" @click="fetchTargetList" :loading="loading" class="refresh-btn">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 目标列表 -->
    <el-card class="target-list-card">
      <el-table
        :data="targetList"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
        highlight-current-row
      >
        <el-table-column prop="name" label="目标名称" width="200"></el-table-column>

        <el-table-column prop="description" label="目标描述" min-width="250"></el-table-column>

        <el-table-column prop="progress" label="完成进度" width="200">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :color="getProgressColor(row.progress)"
              :show-text="row.progress >= 10"
            />
            <span v-if="row.progress < 10" class="progress-text"> {{ row.progress }}% </span>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="150" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column prop="deadline" label="截止日期" width="150" sortable>
          <template #default="{ row }">
            <el-tag :type="getDeadlineTagType(row.deadline)">
              {{ formatDate(row.deadline) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 新增操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)" :icon="Edit">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :small="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增目标对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑目标' : '新增目标'"
      width="50%"
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <el-form :model="targetForm" label-width="100px" label-position="top" class="target-form">
        <el-form-item label="目标名称" required>
          <el-input v-model="targetForm.name" placeholder="请输入目标名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="目标描述">
          <el-input
            v-model="targetForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入目标描述"
            show-word-limit
            maxlength="200"
          ></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="截止日期" required>
              <el-date-picker
                v-model="targetForm.deadline"
                type="date"
                placeholder="选择截止日期"
                :disabled-date="disabledDate"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="完成进度">
              <el-input
                v-model="targetForm.progress"
                type="number"
                :min="0"
                :max="100"
                size="small"
                @change="handleProgressChange"
                class="progress-input-item"
              >
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="form-actions">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitTarget" :loading="submitting">
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Refresh, Edit } from '@element-plus/icons-vue'
import { addTarget, getTargetList, updateTarget } from '@/api/target.js'
import { useUserStore } from '@/stores/user'

const targetForm = ref({
  id: null,
  name: '',
  description: '',
  progress: 0,
  deadline: '',
})

const targetList = ref([])
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const allData = ref([]) // 存储所有数据

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 禁用过去日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 根据进度获取颜色
const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 根据截止日期获取标签类型
const getDeadlineTagType = (deadline) => {
  if (!deadline) return 'info'
  const now = new Date()
  const targetDate = new Date(deadline)
  const diffDays = Math.ceil((targetDate - now) / (1000 * 60 * 60 * 24))

  if (diffDays < 0) return 'danger' // 已过期
  if (diffDays <= 3) return 'warning' // 3天内到期
  return 'success' // 还有时间
}

const user = useUserStore()
// 获取目标列表
const fetchTargetList = async () => {
  try {
    loading.value = true
    const response = await getTargetList(user.user.id)
    allData.value = response.data.data || []
    total.value = allData.value.length // 总条数 = 数组长度

    // 前端分页逻辑
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    targetList.value = allData.value.slice(start, end)
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}



// 提交目标
const isEditMode = ref(false)

// 修改后的表单提交方法
const handleSubmitTarget = async () => {
  if (!targetForm.value.name || !targetForm.value.deadline) {
    ElMessage.error('请填写目标名称和截止日期')
    return
  }

  try {
    submitting.value = true

    if (isEditMode.value) {
      // 编辑模式调用更新接口
      await updateTarget({
        id: targetForm.value.id,
        name: targetForm.value.name,
        description: targetForm.value.description,
        progress: targetForm.value.progress,
        deadline: targetForm.value.deadline,
      })
      ElMessage.success('目标更新成功')
    } else {
      // 新增模式调用添加接口
      const user = 2
      await addTarget({
        userId: user,
        ...targetForm.value,
      })
      ElMessage.success('目标添加成功')
    }

    // 刷新列表并重置状态
    await fetchTargetList()
    resetForm()
    dialogVisible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(isEditMode.value ? '更新目标失败' : '添加目标失败')
  } finally {
    submitting.value = false
  }
}

// 新增目标方法
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑目标方法
const handleEdit = (row) => {
  isEditMode.value = true
  // 填充表单数据
  targetForm.value = {
    id: row.id,
    name: row.name,
    description: row.description,
    progress: row.progress,
    deadline: row.deadline,
  }
  dialogVisible.value = true
}


// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTargetList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTargetList()
}

// 重置表单
const resetForm = () => {
  targetForm.value = {
    id: null,
    name: '',
    description: '',
    progress: 0,
    deadline: '',
  }
}

// 组件挂载时获取目标列表
onMounted(() => {
  fetchTargetList()
})
</script>

<style scoped>
.target-management-container {
  padding: 20px;
}

.header-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.add-target-btn,
.refresh-btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

.target-list-card {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}
.custom-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    &__header {
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
      margin-right: 0;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    &__body {
      padding: 20px;
    }
  }

  .target-form {
    padding: 0 20px;

    .el-form-item {
      margin-bottom: 24px;

      &__label {
        padding-bottom: 8px;
        font-weight: 500;
        color: var(--el-text-color-regular);
      }
    }

    .el-input,
    .el-textarea,
    .el-date-editor {
      :deep(.el-input__wrapper) {
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
      }
    }

    .el-input {
      &__suffix {
        color: var(--el-text-color-placeholder);
      }
    }

    .el-textarea {
      :deep(.el-textarea__inner) {
        border-radius: 8px;
        resize: none;
        min-height: 100px;
      }
    }

    .el-date-editor {
      width: 100%;
    }

    .el-input-number {
      width: 100%;

      :deep(.el-input__wrapper) {
        padding-right: 0;
      }
    }

    .form-actions {
      margin-top: 32px;
      padding-top: 16px;
      border-top: 1px solid var(--el-border-color-light);

      .el-button {
        min-width: 100px;
        border-radius: 8px;
        padding: 10px 20px;

        &--primary {
          font-weight: 500;
        }
      }
    }
  }
}

.progress-input-item {
  width: 100%;
  height: 220%;
}

.progress-text {
  display: inline-block;
  margin-left: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-table :deep(.cell) {
  display: flex;
  align-items: center;
}

.el-progress {
  min-width: 120px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .target-form {
    padding: 0;
  }

  .el-dialog {
    width: 90% !important;
  }
}
</style>
